package com.kl.forum.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kl.forum.dao.*;
import com.kl.forum.entity.*;
import com.kl.forum.enums.PunchClockEnums;
import com.kl.forum.enums.ResultCode;
import com.kl.forum.util.ResultInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import static com.kl.forum.util.DateUtil.*;

@Service
public class PunchClockService {
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private  PunchMatchNoticeMapper punchMatchNoticeMapper;
    //报名
    @Autowired
    private PunchMatchSignMapper punchMatchSignMapper;
    @Autowired
    private PunchMatchRecordMapper punchMatchRecordMapper;
    @Autowired
    private PunchClockMapper punchClockMapper;
    @Autowired
    private PunchMatchConfigMapper punchMatchConfigMapper;

    public ResultInfo punchClock(Integer userId,Integer configId) {
        Date date=new Date();
        ResultInfo  re =new ResultInfo();
        Map<String,Object> map=new HashMap<>();
        PunchMatchRecord punchMatchRecord1=new PunchMatchRecord();
       try {
           //查询所有进行的赛事 is_del=1
//            List<PunchMatchRecord> matchRecordList= punchMatchRecordMapper.findPunchMatch();
            //查询正在进行的赛事  根据配置Id
            PunchMatchRecord punchMatchRecord= punchMatchRecordMapper.findPunchMatchByConfigId(configId);
            if (punchMatchRecord!=null){
                long time=24*60*60*1000;
                long time1=getTimeDelta(date,  addDays(getCurDateWith5(),1));
                if(time1>time){
                    map.put("nowTime",time1-time);
                }else {
                    map.put("nowTime",getTimeDelta(date,  addDays(getCurDateWith5() ,1)));
                }

            }else {
                map.put("punchClockStatus", PunchClockEnums.结算.getCode());
            }
            map.put("punchClockStatus", PunchClockEnums.默认.getCode());
            PunchMatchSign punchMatchSign= punchMatchSignMapper.findOneMatchSign(userId,punchMatchRecord.getId());
            //是否参加了活动
            if (punchMatchSign!=null) {
//                PunchMatchConfig punchMatchConfig= punchMatchConfigMapper.selectByPrimaryKey(punchMatchSign.getMatchConfigId());
                map.put("punchMatchSign", punchMatchSign);
                map.put("punchMatchRecord", punchMatchRecord);
                map.put("punchClockStatus", PunchClockEnums.倒计时.getCode());
                PunchClock punchClock1=punchClockMapper.findOneDayPunchClock(userId,punchMatchSign.getMatchId(),date);
                if (is58()&&punchClock1!=null){
                    map.put("punchClockStatus", PunchClockEnums.成功.getCode());
                }
                if (is58()&&punchClock1==null){
                    map.put("punchClockStatus", PunchClockEnums.打卡.getCode());
                }
            }else {
                punchMatchRecord= punchMatchRecordMapper.findPunchMatchByConfigId(configId);
                map.put("punchMatchRecord", punchMatchRecord);
                map.put("punchMatchSign", null);
            }
            if (punchMatchRecord != null) {
                Date date1 = addDays(punchMatchRecord.getCreateTime(), -punchMatchRecord.getDayNum());
                //上次打卡战况
                 punchMatchRecord1 = punchMatchRecordMapper.findPunchMatchYesterday(date1, punchMatchRecord.getConfigId());
                if(punchMatchRecord1!=null){
                    int winNum = punchMatchSignMapper.findMatchSignCountWin(punchMatchRecord1.getId(), 1);
                    int loseNum = punchMatchSignMapper.findMatchSignCountWin(punchMatchRecord1.getId(), 0);
                    map.put("winNum", winNum);
                    map.put("loseNum", loseNum);
                }else {
                    map.put("winNum", 0);
                    map.put("loseNum", 0);
                }

            }
            map.put("listLight",null);
            if (punchMatchSign!=null&&punchMatchRecord!=null){
                List<PunchClock> list=  punchClockMapper.findPunchClock(userId,punchMatchSign.getMatchId());
                if (list.size()>0&&list!=null){
                    List listLight=new ArrayList();
                    for (int i=0;i<list.size();i++){
                        int n=differentDays(punchMatchRecord.getStartTime(),list.get(i).getCreateTime());
                        System.out.println(n);
                        listLight.add(n);
                    }
                    //灯的状态
                    map.put("listLight",listLight);
                }
            }
            //最早
           if (punchMatchRecord1!=null){
               PunchClock punchClock= punchClockMapper.findUserZao(punchMatchRecord.getConfigId(),punchMatchRecord1.getId());
               map.put("userZao",punchClock);
           }else {
               map.put("userZao",null);
           }
            //打卡最多
            PunchMatchSign punchMatchSign1=punchMatchSignMapper.findUserWins(punchMatchRecord.getConfigId());
            map.put("userDuo",punchMatchSign1);
            //坚持最久
            PunchMatchSign userLong=punchMatchSignMapper.findUserLong(punchMatchRecord.getConfigId());
            if (userLong==null){
                map.put("userLong",null);
            }else {
                Member m= memberMapper.findUserByUserId(userLong.getUserId());
                map.put("userLong",m);

            }
                //累计投入金币
                Integer giveGold= punchMatchSignMapper.findMatchSignGiveGold(userId,punchMatchRecord.getConfigId());
                //累计瓜分金币
                Integer getGold= punchMatchSignMapper.findMatchSignGetGold(userId,punchMatchRecord.getConfigId());
                //成功打卡N次
                Integer myWins= punchMatchSignMapper.findMyMatchSignCountWin(userId,punchMatchRecord.getConfigId());
                map.put("giveGold",giveGold);
                map.put("getGold",getGold);
                map.put("myWins",myWins);
            re.setData(map);
            re.setMessage(ResultCode.SUCCESS.getMsg());
            re.setCode(ResultCode.SUCCESS.getCode());
            return  re;
        }catch (Exception e){
            e.printStackTrace();
        }
        re.setMessage(ResultCode.SUCCESS.getMsg());
        re.setCode(ResultCode.SUCCESS.getCode());
        return  re;
    }

    public ResultInfo addClock(Integer userId, Integer configId,Integer matchId) {
        ResultInfo re=new ResultInfo();
        PunchMatchConfig punchMatchConfig= punchMatchConfigMapper.selectByPrimaryKey(configId);
        PunchMatchRecord record1=punchMatchRecordMapper.findPunchMatchByConfigIdIng(configId);
        Date dd[]=new Date[2];
        Date startTime= record1.getStartTime();
        Date endTime=getCurDateWithMaxTime(record1.getStartTime());
        dd[0]=startTime;
        dd[1]=endTime;
        Boolean b= belongCalendar(new Date(),startTime,endTime);
        try {
            if (b){
                Member member= memberMapper.findUserByUserId(userId);
                PunchMatchSign punchMatchSign1= punchMatchSignMapper.findMatchSignIngByUserId(userId);
                if (punchMatchSign1==null){
                    if (member.getCoinNumber()>=punchMatchConfig.getGoldNum()){
                        PunchMatchSign punchMatchSign=new PunchMatchSign();
                        punchMatchSign.setMatchId(matchId);
                        punchMatchSign.setDayNum(0);
                        punchMatchSign.setCreateTime(new Date());
                        punchMatchSign.setIsDel(Byte.parseByte("1"));
                        punchMatchSign.setStatus(2);
                        punchMatchSign.setGiveGoldNum(punchMatchConfig.getGoldNum());
                        punchMatchSign.setGetGoldNum(0);
                        punchMatchSign.setUserId(userId);
                        punchMatchSign.setMatchConfigId(configId);
                        punchMatchSignMapper.insertSelective(punchMatchSign);
                        PunchMatchRecord record=punchMatchRecordMapper.selectByPrimaryKey(matchId);
                        record.setGoldNum(record.getGoldNum()+punchMatchConfig.getGoldNum());
                        record.setNumber(record.getNumber()+1);
                        punchMatchRecordMapper.updateByPrimaryKeySelective(record);
                        member.setCoinNumber(member.getCoinNumber()-punchMatchConfig.getGoldNum());
                        memberMapper.updateByPrimaryKeySelective(member);
                        re.setData("恭喜您成功参与挑战，记得明天准时来打卡哦！");
                        re.setMessage(ResultCode.SUCCESS.getMsg());
                        re.setCode(ResultCode.SUCCESS.getCode());
                        return  re;
                    }else {
                        re.setData("您的金币不足，无法参与挑战！");
                        re.setMessage(ResultCode.SUCCESS.getMsg());
                        re.setCode(ResultCode.SUCCESS.getCode());
                        return  re;
                    }
                }else {
                    re.setData("您已参与其他打卡挑战赛，不能同时参与2个！");
                    re.setMessage(ResultCode.SUCCESS.getMsg());
                    re.setCode(ResultCode.SUCCESS.getCode());
                    return  re;
                }
            }else {
                re.setData("报名失败，当前时间不可报名！");
                re.setMessage(ResultCode.SUCCESS.getMsg());
                re.setCode(PunchClockEnums.默认.getCode());
                return  re;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        re.setMessage(ResultCode.SUCCESS.getMsg());
        re.setCode(ResultCode.SUCCESS.getCode());
        return  re;
    }


    public ResultInfo findPunchClockGame() {
        ResultInfo re=new ResultInfo();
        try {
            PageHelper.startPage(1, 10);
            List<PunchMatchConfig> configList=punchMatchConfigMapper.findPunchMatchConfigList();
                for (PunchMatchConfig   config :configList){
                    PunchMatchRecord record=   punchMatchRecordMapper.findPunchMatchByConfigIdTopOne(config.getId());
                    Integer  count=  punchMatchSignMapper.findCountSum(record.getId());
                    config.setCountNumber(count);
                    config.setMatchStartTime(record.getStartTime());
                    config.setMatchEndTime(record.getEndTime());
                }
            PageInfo<PunchMatchConfig> pageInfo = new PageInfo<>(configList);
            re.setData(pageInfo);
            re.setMessage(ResultCode.SUCCESS.getMsg());
            re.setCode(ResultCode.SUCCESS.getCode());
            return re;
        }catch (Exception e){
            e.printStackTrace();
        }
        re.setMessage(ResultCode.SUCCESS.getMsg());
        re.setCode(ResultCode.SUCCESS.getCode());
        return  re;
    }

    public ResultInfo findMyPunchMatch(Integer userId, Integer configId,Integer pageNum,Integer pageSize) {
        ResultInfo re=new ResultInfo();
        try {
            PageHelper.startPage(pageNum, pageSize);
            List<PunchMatchSign> signList=punchMatchSignMapper.findPunchMatchConfigList(userId,configId);
            PageInfo<PunchMatchSign> pageInfo = new PageInfo<>(signList);
            re.setData(pageInfo);
            re.setMessage(ResultCode.SUCCESS.getMsg());
            re.setCode(ResultCode.SUCCESS.getCode());
            return re;
        }catch (Exception e){
            e.printStackTrace();
        }
        re.setMessage(ResultCode.SUCCESS.getMsg());
        re.setCode(ResultCode.SUCCESS.getCode());
        return  re;
    }

    public ResultInfo clockIn(Integer userId,Integer configId, Integer matchId) {
        Date date=new Date();
        ResultInfo  re =new ResultInfo();
        try {
            PunchMatchSign punchMatchSign= punchMatchSignMapper.findOneMatchSign(userId,matchId);
            PunchClock punchClock1=punchClockMapper.findOneDayPunchClock(userId,matchId,date);
            PunchMatchConfig punchMatchConfig= punchMatchConfigMapper.selectByPrimaryKey(configId);
            if (punchClock1==null&&is58()){
                PunchClock punchClock=new PunchClock();
                punchClock.setUserId(userId);
                punchClock.setCreateTime(new Date());
                punchClock.setStatus(1);
                punchClock.setMatchId(matchId);
                punchClock.setMatchConfigId(configId);
                punchClockMapper.insertSelective(punchClock);
                if((punchMatchSign.getDayNum()+1)==punchMatchConfig.getDayNum()){
                    punchMatchSign.setStatus(1);
                }
                punchMatchSign.setDayNum(punchMatchSign.getDayNum()+1);
                punchMatchSignMapper.updateByPrimaryKeySelective(punchMatchSign);
                re.setData("打卡成功");
                re.setMessage(ResultCode.SUCCESS.getMsg());
                re.setCode(ResultCode.SUCCESS.getCode());
                return  re;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        re.setData("打卡失败，已过期");
        re.setMessage(ResultCode.SUCCESS.getMsg());
        re.setCode(ResultCode.SUCCESS.getCode());
        return  re;
    }


    public static boolean  is58(){
        Date dd[]=new Date[2];
        Date startTime= getCurDateWith5();
        Date endTime=getCurDateWith8Int();
        Calendar c = Calendar.getInstance();
        Boolean is58= belongCalendar (c.getTime(),startTime,endTime);
        return  is58;
    }



    public ResultInfo addNotice(Integer userId,Integer matchId) {
        ResultInfo re=new ResultInfo();
        try {
            PunchMatchNotice punchMatchNotice= punchMatchNoticeMapper.findMatchNoticeByUserId(userId);
            if (punchMatchNotice!=null){
                if (punchMatchNotice.getIsDel()==1){
                    re.setData("已预约！");
                    re.setMessage(ResultCode.SUCCESS.getMsg());
                    re.setCode(ResultCode.SUCCESS.getCode());
                    return  re;
                }else {
                    punchMatchNotice.setIsDel(1);
                    punchMatchNotice.setCreateTime(new Date());
                    punchMatchNotice.setMatchId(matchId);
                    punchMatchNoticeMapper.updateByPrimaryKeySelective(punchMatchNotice);
                    re.setData("成功");
                    re.setMessage(ResultCode.SUCCESS.getMsg());
                    re.setCode(ResultCode.SUCCESS.getCode());
                    return  re;
                }
            }else {
                PunchMatchNotice notice=new PunchMatchNotice();
                notice.setCreateTime(new Date());
                notice.setIsDel(1);
                notice.setUserId(userId);
                notice.setMatchId(matchId);
                punchMatchNoticeMapper.insertSelective(notice);
                re.setData("成功");
                re.setMessage(ResultCode.SUCCESS.getMsg());
                re.setCode(ResultCode.SUCCESS.getCode());
                return  re;
            }


        }catch (Exception e){
            e.printStackTrace();
        }
        re.setMessage(ResultCode.SUCCESS.getMsg());
        re.setCode(ResultCode.SUCCESS.getCode());
        return  re;
    }
}
